package main;

import game.BeautyContest;
import game.Centipede;
import game.Dilemma;
import game.Dictator;
import game.Game;
import game.Impulse;
import game.Lottery;
import game.Penelope;
import game.PublicGoods;
import game.Rev_Centipede;
import game.Rev_Dictator;
import game.Rev_Trust;
import game.Rev_Ulti;
import game.Trust;
import game.TrustDictator;
import game.Ultimatum;
import game.Questionnaire;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Vector;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;

/**
 *
 * @author Vinay
 */
public class Runner extends JFrame
{
    static Vector<String> gameParamList = new Vector<String>();
    static Game g = new Game();
    static Dimension screenSize;
            
    static JDesktopPane desktop;

    private static final String MOV_REPEAT_STR = "-Repeated";
    private static final String PLAYER2_STR = "-Player2";
    
    public Runner() {
        super("");

        screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        setUndecorated(true);
      
        setBounds(0, 0,
                  screenSize.width,
                  screenSize.height);

        //Set up the GUI.
        desktop = new JDesktopPane();//a specialized layered pane
        desktop.setSize(850, 650);
        setContentPane(desktop);

		g.runner = this;
    }

    public static void getList() {
        try {
            BufferedReader br = g.readFile("list.txt");
            String line="";
            while((line=br.readLine())!=null) {
                gameParamList.add(line);
            }
        } catch(Exception ex) {
            ex.printStackTrace();
            g.logError(ex);
        }
    }

    public static void runGameIntroduction (String currentGame) {
        if (!g.debugMode) {

            if(g.played.containsKey(currentGame) && g.played.get(currentGame)) {
                runInstructionMovie(currentGame+MOV_REPEAT_STR);
            }
            else {
                runInstructionMovie(currentGame);
                runInstructions(currentGame);
                g.played.put(currentGame, true);
            }
        }
    }

    public static void runConfigScreen() {
        g.free = false;
        ConfigScreen config = new ConfigScreen();
        config.setLocation(screenSize.width/2-g.WIDTH/2, screenSize.height/2-g.HEIGHT/2);
        while(!g.free) {
            System.err.print("");
        };
        gameParamList = config.getGameParamsList();
    }

    public static void runInstructionMovie(String game) {
        g.free = false;
        InstructionMovie instMov = new InstructionMovie(game);
        desktop.add(instMov);
        instMov.setLocation(screenSize.width/2-g.WIDTH/2, screenSize.height/2-g.HEIGHT/2);
        while(!g.free) {
            System.err.print("");
        };
        desktop.remove(instMov);
    }

    public static void runInstructions(String game) {
        g.free = false;
        Instructions inst = new Instructions(game);
        desktop.add(inst);
        inst.setLocation(screenSize.width/2-g.WIDTH/2, screenSize.height/2-g.HEIGHT/2);
        while(!g.free) {
            System.err.print("");
        };
        desktop.remove(inst);
        runQuiz(game);
    }

    public static void runQuiz(String game) {
        g.free = false;
        Quiz qz = new Quiz(game);
        desktop.add(qz);
        qz.setLocation(screenSize.width/2-g.WIDTH/2, screenSize.height/2-g.HEIGHT/2);
        while(!g.free) {
            System.err.print("");
        };
        desktop.remove(qz);
    }

    public static void runResult (String result, String inst) {
        //g.free = false;
        Result res = new Result(result, inst);
        desktop.add(res);
        res.setLocation(screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        //while(!g.free);
    }

    public static void runPenelope (String params, int currentRep) {
        g.free = false;

        System.err.println("[DEBUG]: Running Penelope");
        Penelope game = new Penelope (params, currentRep);
        desktop.add (game);
        game.setLocation (screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while (!g.free) {
            System.err.print("");
        };
        desktop.remove (game);
    }

    public static void runImpulse (String params, int currentRep) {
        g.free = false;

        System.err.println("[DEBUG]: Running Impulse");
        Impulse game = new Impulse (params, currentRep);
        desktop.add (game);
        game.setLocation (screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while (!g.free) {
            System.err.print("");
        };
        desktop.remove (game);
    }

	public static void runLottery (String params, int currentRep) {
        g.free = false;

        System.err.println("[DEBUG]: Running Lottery");
        Lottery game = new Lottery (params, currentRep);
        desktop.add (game);
        game.setLocation (screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while (!g.free) {
            System.err.print("");
        };
        desktop.remove (game);
    }

	public static void runDictatorPlayer1 (String params, int currentRep) {
        g.free = false;

		System.err.println("[DEBUG]: Running Dictator-Player1");
        Dictator game = new Dictator (params, currentRep);
        desktop.add (game);
        game.setLocation (screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while (!g.free) {
            System.err.print("");
        };
        desktop.remove (game);
    }

    public static void runDictatorPlayer2 (String params, int currentRep) {
        g.free = false;

		System.err.println("[DEBUG]: Running Dictator-Player2");
        Rev_Dictator game = new Rev_Dictator (params, currentRep);
        desktop.add(game);
        game.setLocation(screenSize.width/2-g.WIDTH/2, screenSize.height/2-g.HEIGHT/2);
        while(!g.free) {
            System.err.print("");
        };
        desktop.remove(game);
    }

	public static void runUltimatumPlayer1 (String params, int currentRep) {
        g.free = false;

		System.err.println("[DEBUG]: Running Ultimatum-Player1");
        Ultimatum game = new Ultimatum (params, currentRep);
        desktop.add(game);
        game.setLocation (screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while (!g.free) {
            System.err.print("");
        };
        desktop.remove (game);
    }

    public static void runUltimatumPlayer2 (String params, int currentRep) {
        g.free = false;

		System.err.println("[DEBUG]: Running Ultimatum-Player2");
        Rev_Ulti game = new Rev_Ulti(params, currentRep);
        desktop.add(game);
        game.setLocation(screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while(!g.free) {
            System.err.print("");
        };
        desktop.remove(game);
    }

	public static void runTrustPlayer1 (String params, int currentRep) {
        g.free = false;

		System.err.println("[DEBUG]: Running Trust-Player1");
        Trust game = new Trust(params, currentRep);
        desktop.add (game);
        game.setLocation (screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while (!g.free) {
            System.err.print("");
        };
        desktop.remove (game);
    }

    public static void runTrustPlayer2 (String params, int currentRep) {
        g.free = false;

		System.err.println("[DEBUG]: Running Trust-Player2");
        Rev_Trust game = new Rev_Trust (params, currentRep);
        desktop.add (game);
        game.setLocation (screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while (!g.free) {
            System.err.print("");
        };
        desktop.remove (game);
    }

	public static void runTrustDictator (String params, int currentRep) {
        // Note: Trust-Dictator delegates to Dictator.
		TrustDictator game = new TrustDictator (params, currentRep);
    }

	public static void runCentipedePlayer1 (String params, int currentRep) {
        g.free = false;

		System.err.println("[DEBUG]: Running Centipede-Player1");
        Centipede game = new Centipede(params, currentRep);
        desktop.add(game);
        game.setLocation(screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while(!g.free) {
            System.err.print("");
        };
        desktop.remove(game);
    }

    public static void runCentipedePlayer2 (String params, int currentRep) {
        g.free = false;

		System.err.println("[DEBUG]: Running Centipede-Player2");
        Rev_Centipede game = new Rev_Centipede (params, currentRep);
        desktop.add (game);
        game.setLocation (screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while (!g.free) {
            System.err.print("");
        };
        desktop.remove (game);
    }

	public static void runDilemma(String params, int currentRep) {
        g.free = false;

        System.err.println("[DEBUG]: Running Dilemma");
        Dilemma game = new Dilemma(params, currentRep);
        game.setVisible(true);
        desktop.add(game);
        game.setLocation(screenSize.width/2-g.WIDTH/2, screenSize.height/2-g.HEIGHT/2);
        game.setBorder(null);
        while(!g.free) {
            System.err.print("");
        };
        desktop.remove(game);
    }

    public static void runBeautyContest (String params, int currentRep) {
        g.free = false;

        System.err.println("[DEBUG]: Running BeautyContest");
        BeautyContest game = new BeautyContest (params, currentRep);
        desktop.add(game);
        game.setLocation(screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while(!g.free) {
            System.err.print("");
        };
        desktop.remove(game);
    }

	public static void runPublicGoods (String params, int currentRep) {
        g.free = false;

        System.err.println("[DEBUG]: Running Public-Goods");
        PublicGoods game = new PublicGoods (params, currentRep);
        desktop.add(game);
        game.setLocation(screenSize.width/2-g.WIDTH/2,
                screenSize.height/2-g.HEIGHT/2);
        while(!g.free) {
            System.err.print("");
        };
        desktop.remove(game);
    }

    public static void runQuestionnaire (String params, int currentRep) {
        g.free=false;

		System.err.println("[DEBUG]: Running Questionnaire");
        Questionnaire game = new Questionnaire (params, currentRep);
        desktop.add(game);
        game.setLocation(screenSize.width/2-g.WIDTH/2, screenSize.height/2-g.HEIGHT/2);
        while(!g.free) {
            System.err.print("");
        };
        desktop.remove(game);
    }

    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        //JFrame.setDefaultLookAndFeelDecorated(true);

        //Create and set up the window.
        Runner frame = new Runner();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Display the window.
        frame.setVisible(true);
    }

    private static void generatePlayerID() {
        try {
            String compName = InetAddress.getLocalHost().getHostName();
            Calendar cal = Calendar.getInstance();
            final String DATE_FORMAT_NOW = "yyyy-MM-dd#HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
            String dateTime = sdf.format(cal.getTime());
            g.playerId = ""+compName+"#"+dateTime;
            System.out.println("PlayerID : "+compName+"#"+dateTime);
        } catch(Exception ex) {
            ex.printStackTrace();
            g.logError(ex);
        }
    }

    public static void main(String args[]) {
//        try
//        {
//            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
//        }
//        catch (UnsupportedLookAndFeelException e)
//        {
//           // handle exception
//        }
//        catch (ClassNotFoundException e)
//        {
//           // handle exception
//        }
//        catch (InstantiationException e)
//        {
//           // handle exception
//        }
//        catch (IllegalAccessException e)
//        {
//           // handle exception
//        }

        if (args.length != 0)
        {
            if (args[0].equals("debug"))
                g.debugMode = true;
        }
        createAndShowGUI();
        generatePlayerID();
        runConfigScreen();
        System.out.println("paramList size is : "+gameParamList.size());
        /*g.writeLog("*********************************************************************");
        g.writeLog("Player ID : "+g.playerId);
        g.writeLog("---------------------------------------------------------------------");*/
        for(int i=0; i<gameParamList.size(); i++) {
            String linePart[] = gameParamList.get(i).split(",");
            g.played.clear();

            g.currGame = linePart[0];
            int numRepetitions = Integer.parseInt(linePart[1]);
            System.out.println("currGame = "+g.currGame);
            
            if (linePart[0].equals("Penelope")) {
                for (int rep=0; rep<numRepetitions; rep++) {
                    runGameIntroduction (linePart[0]);
                    runPenelope(gameParamList.get(i), rep + 1);
                }
            }
			else if(linePart[0].equals("Impulse")) {
                for (int rep=0; rep<numRepetitions; rep++) {
                    runGameIntroduction (linePart[0]);
                    runImpulse(gameParamList.get(i), rep + 1);
                }
            }
			else if(linePart[0].equals("Lottery")) {
                for (int rep=0; rep<numRepetitions; rep++) {
                    runGameIntroduction (linePart[0]);
                    runLottery(gameParamList.get(i), rep + 1);
                }
            }
			else if(linePart[0].equals("Dictator")) {
                for (int rep=0; rep<numRepetitions; rep++) {
                    String currentGame = linePart[0];
                    if (Math.floor(Math.random() * 2) == 0) {
                        runGameIntroduction (currentGame);
                        runDictatorPlayer1(gameParamList.get(i), rep + 1);

                        currentGame += PLAYER2_STR;
                        runGameIntroduction (currentGame);
                        runDictatorPlayer2 (gameParamList.get(i), rep + 1);
                    }
                    else {
                        currentGame += PLAYER2_STR;
                        runGameIntroduction (currentGame);
                        runDictatorPlayer2 (gameParamList.get(i), rep + 1);

                        currentGame = linePart[0];
                        runGameIntroduction (currentGame);
                        runDictatorPlayer1 (gameParamList.get(i), rep + 1);
                    }
                }
            }
            else if(linePart[0].equals("Ultimatum")) {
                for (int rep=0; rep<numRepetitions; rep++) {
                    String currentGame = linePart[0];
                    if (Math.floor(Math.random() * 2) == 0) {
                        runGameIntroduction (currentGame);
                        runUltimatumPlayer1(gameParamList.get(i), rep + 1);

                        currentGame += PLAYER2_STR;
                        runGameIntroduction (currentGame);
                        runUltimatumPlayer2 (gameParamList.get(i), rep + 1);
                    }
                    else {
                        currentGame += PLAYER2_STR;
                        runGameIntroduction (currentGame);
                        runUltimatumPlayer2 (gameParamList.get(i), rep + 1);

                        currentGame = linePart[0];
                        runGameIntroduction (currentGame);
                        runUltimatumPlayer1 (gameParamList.get(i), rep + 1);
                    }
                }
            }
			else if(linePart[0].equals("Trust")) {
                for (int rep=0; rep<numRepetitions; rep++) {
                    String currentGame = linePart[0];
                    if (Math.floor(Math.random() * 2) == 0) {
                        runGameIntroduction (currentGame);
                        runTrustPlayer1(gameParamList.get(i), rep + 1);

                        currentGame += PLAYER2_STR;
                        runGameIntroduction (currentGame);
                        runTrustPlayer2 (gameParamList.get(i), rep + 1);
                    }
                    else {
                        currentGame += PLAYER2_STR;
                        runGameIntroduction (currentGame);
                        runTrustPlayer2 (gameParamList.get(i), rep + 1);

                        currentGame = linePart[0];
                        runGameIntroduction (currentGame);
                        runTrustPlayer1 (gameParamList.get(i), rep + 1);
                    }
                }
            }
			else if(linePart[0].equals("Trust-Dictator")) {
                for (int rep=0; rep<numRepetitions; rep++) {
                    runGameIntroduction (linePart[0]);
                    runTrustDictator(gameParamList.get(i), rep + 1);
                }
            }
			else if(linePart[0].equals("Centipede")) {
                for (int rep=0; rep<numRepetitions; rep++) {
                    String currentGame = linePart[0];
                    if (Math.floor(Math.random() * 2) == 0) {
                        runGameIntroduction (currentGame);
                        runCentipedePlayer1 (gameParamList.get(i), rep + 1);

						currentGame += PLAYER2_STR;
						runGameIntroduction (currentGame);
						runCentipedePlayer2 (gameParamList.get(i), rep + 1);
                    }
                    else {
                        currentGame += PLAYER2_STR;
                        runGameIntroduction (currentGame);
                        runCentipedePlayer2 (gameParamList.get(i), rep + 1);

						currentGame = linePart[0];
						runGameIntroduction (currentGame);
						runCentipedePlayer1 (gameParamList.get(i), rep + 1);
                    }
                }
            }
            else if(linePart[0].equals("Dilemma")) {
                for (int rep=0; rep<numRepetitions; rep++) {
                    runGameIntroduction (linePart[0]);
                    runDilemma(gameParamList.get(i), rep + 1);
                }
            }
            else if(linePart[0].equals("Beauty-Contest")) {
                for (int rep=0; rep<numRepetitions; rep++) {
                    runGameIntroduction (linePart[0]);
                    runBeautyContest(gameParamList.get(i), rep + 1);
                }
            }
			else if(linePart[0].equals("Public-Goods")) {
                for (int rep=0; rep<numRepetitions; rep++) {
                    runGameIntroduction (linePart[0]);
                    runPublicGoods(gameParamList.get(i), rep + 1);
                }
            }
            else if(linePart[0].equals("Questionnaire")) {
				for (int rep=0; rep<numRepetitions; rep++) {
					runQuestionnaire (gameParamList.get(i), rep + 1);
				}
            }
        }
        runResult ("You won a total of $" +
                String.format ("%.2f",g.totalMoneyWon) + " !!",
                "Please wait for the examiner to arrive ..");
        /*g.writeLog("---------------------------------------------------------------------");
        g.writeLog("Total money Won : $" + String.format ("%.2f",g.totalMoneyWon));
        g.writeLog("*********************************************************************");*/
        //System.exit(0);
    }

}
